package me.luraframework.db.criteria;

import cn.hutool.core.util.ObjectUtil;
import me.luraframework.commons.annotation.Query;
import me.luraframework.db.exception.PredicateGenerateException;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * @description: 基于Jpa Specification的查询工具
 * @author: Liu Ran
 * @data: 10/27/22 10:20
 */
@Slf4j
@SuppressWarnings({"unchecked","all"})
public class QueryHelper {

    public static <R, Q> Predicate getPredicate(Root<R> root, Q query, CriteriaBuilder cb) {
        List<Predicate> list = new ArrayList<>();

        if (Objects.isNull(query)) {
            return cb.and(list.toArray(new Predicate[0]));
        }

        try {
            List<Field> fields = getAllFields(query.getClass(), new ArrayList<>());
            for (Field field : fields) {
                Query q = field.getAnnotation(Query.class);
                if (Objects.isNull(q)) {
                    continue;
                }
                String propName = q.propName();
                String blurry = q.blurry();
                String attributeName = Strings.isNullOrEmpty(propName) ? field.getName() : propName;
                Class<?> fieldType = field.getType();
                String joinName = q.joinName();

                boolean accessible = field.isAccessible();
                field.setAccessible(true);
                Object val = field.get(query);
                field.setAccessible(accessible);
                if (Objects.isNull(val) || "".equals(val)) {
                    continue;
                }

                Join join = null;
                if (!Strings.isNullOrEmpty(joinName)) {
                    switch (q.join()) {
                        case INNER:
                            join = root.join(joinName, JoinType.INNER);
                            break;
                        case RIGHT:
                            join = root.join(joinName, JoinType.RIGHT);
                            break;
                        case LEFT:
                            join = root.join(joinName, JoinType.LEFT);
                            break;
                        default:
                            break;
                    }
                }

                // 模糊多字段
                if (ObjectUtil.isNotEmpty(blurry)) {
                    String[] blurrys = blurry.split(",");
                    List<Predicate> orPredicate = new ArrayList<>();
                    for (String s : blurrys) {
                        orPredicate.add(cb.like(getExpression(s, join, root)
                                .as(String.class), "%" + val.toString() + "%"));
                    }
                    Predicate[] p = new Predicate[orPredicate.size()];
                    list.add(cb.or(orPredicate.toArray(p)));
                    continue;
                }

                switch (q.type()) {
                    case EQUAL:
                        list.add(cb.equal(getExpression(attributeName, join, root).as(fieldType), val));
                        break;
                    case NOT_EQUAL:
                        list.add(cb.notEqual(getExpression(attributeName, join, root).as(fieldType), val));
                        break;
                    case LEFT_LIKE:
                        list.add(cb.like(getExpression(attributeName, join, root)
                                .as(String.class), val + "%"));
                        break;
                    case INNER_LIKE:
                        list.add(cb.like(getExpression(attributeName, join, root)
                                .as(String.class), "%" + val + "%"));
                        break;
                    case RIGHT_LIKE:
                        list.add(cb.like(getExpression(attributeName, join, root)
                                .as(String.class), "%" + val));
                        break;
                    case GREATER_THAN_EQ:
                        list.add(cb.greaterThanOrEqualTo(getExpression(attributeName, join, root)
                                .as((Class<? extends Comparable>) fieldType), (Comparable) val));
                        break;
                    case GREATER_THAN:
                        list.add(cb.greaterThan(getExpression(attributeName, join, root)
                                .as((Class<? extends Comparable>) fieldType), (Comparable) val));
                        break;
                    case LESS_THAN_EQ:
                        list.add(cb.lessThanOrEqualTo(getExpression(attributeName, join, root)
                                .as((Class<? extends Comparable>) fieldType), (Comparable) val));
                        break;
                    case LESS_THAN:
                        list.add(cb.lessThan(getExpression(attributeName, join, root)
                                .as((Class<? extends Comparable>) fieldType), (Comparable) val));
                        break;
                    case NOT_NULL:
                        if (val instanceof Boolean && (Boolean) val) {
                            list.add(getExpression(attributeName, join, root).isNotNull());
                        }
                        break;
                    case IS_NULL:
                        if (val instanceof Boolean && (Boolean) val) {
                            list.add(getExpression(attributeName, join, root).isNull());
                        }
                        break;
                    case IN:
                        list.add(getExpression(attributeName, join, root).in((Collection<Object>)val));
                        break;
                    case NOT_IN:
                        list.add(getExpression(attributeName, join, root).in((Collection<Object>)val).not());
                        break;
                    case BETWEEN:
                        List<? extends Comparable> between = new ArrayList<>((List<? extends Comparable>) val);
                        list.add(cb.between(getExpression(attributeName, join, root)
                                .as(between.get(0).getClass()), between.get(0), between.get(1)));
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new PredicateGenerateException(e);
        }


        return cb.and(list.toArray(new Predicate[0]));

    }

    private static <R, T> Expression<T> getExpression(String attributeName, Join join, Root<R> root) {
        if (Objects.nonNull(join)) {
            return join.get(attributeName);
        } else {
            return root.get(attributeName);
        }
    }

    public static <Q> List<Field> getAllFields(Class<?> clazz, List<Field> fields) {
        if (Objects.nonNull(clazz)) {
            fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
            return getAllFields(clazz.getSuperclass(), fields);
        }
        return fields;
    }
}
